<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑考核' : '新增考核'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="人员姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入人员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-select v-model="formData.department" placeholder="请选择所属部门" style="width: 100%">
              <el-option label="管理部" value="管理部" />
              <el-option label="运行部" value="运行部" />
              <el-option label="维护部" value="维护部" />
              <el-option label="安全部" value="安全部" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考核期间" prop="evaluationPeriod">
            <el-date-picker
              v-model="formData.evaluationPeriod"
              type="month"
              placeholder="请选择考核期间"
              format="YYYY-MM"
              value-format="YYYY-MM"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考核人" prop="evaluator">
            <el-input v-model="formData.evaluator" placeholder="请输入考核人" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="责任履行" prop="responsibilityScore">
            <el-input-number
              v-model="formData.responsibilityScore"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="请输入分数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务完成" prop="taskCompletion">
            <el-input-number
              v-model="formData.taskCompletion"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="请输入分数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总分" prop="totalScore">
            <el-input-number
              v-model="formData.totalScore"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="自动计算"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考核等级" prop="grade">
            <el-select v-model="formData.grade" placeholder="请选择考核等级" style="width: 100%">
              <el-option label="优秀" value="excellent" />
              <el-option label="良好" value="good" />
              <el-option label="合格" value="qualified" />
              <el-option label="不合格" value="unqualified" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考核时间" prop="evaluationDate">
            <el-date-picker
              v-model="formData.evaluationDate"
              type="datetime"
              placeholder="请选择考核时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="考核备注">
        <el-input
          v-model="formData.remarks"
          type="textarea"
          :rows="4"
          placeholder="请输入考核备注"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  evaluationData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  evaluationData: null
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.evaluationData?.id)

const formData = reactive({
  name: '',
  department: '',
  evaluationPeriod: '',
  evaluator: '',
  responsibilityScore: 0,
  taskCompletion: 0,
  totalScore: 0,
  grade: '',
  evaluationDate: '',
  remarks: ''
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  evaluationPeriod: [
    { required: true, message: '请选择考核期间', trigger: 'change' }
  ],
  evaluator: [
    { required: true, message: '请输入考核人', trigger: 'blur' }
  ],
  responsibilityScore: [
    { required: true, message: '请输入责任履行分数', trigger: 'blur' }
  ],
  taskCompletion: [
    { required: true, message: '请输入任务完成分数', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择考核等级', trigger: 'change' }
  ],
  evaluationDate: [
    { required: true, message: '请选择考核时间', trigger: 'change' }
  ]
}

// 监听分数变化，自动计算总分
watch([() => formData.responsibilityScore, () => formData.taskCompletion], ([score1, score2]) => {
  if (score1 && score2) {
    formData.totalScore = Number(((score1 + score2) / 2).toFixed(1))
    
    // 根据总分自动设置等级
    if (formData.totalScore >= 90) {
      formData.grade = 'excellent'
    } else if (formData.totalScore >= 80) {
      formData.grade = 'good'
    } else if (formData.totalScore >= 70) {
      formData.grade = 'qualified'
    } else {
      formData.grade = 'unqualified'
    }
  }
})

// 重置表单函数
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    department: '',
    evaluationPeriod: '',
    evaluator: '',
    responsibilityScore: 0,
    taskCompletion: 0,
    totalScore: 0,
    grade: '',
    evaluationDate: '',
    remarks: ''
  })
  formRef.value?.clearValidate()
}

// 监听数据变化，初始化表单
watch(() => props.evaluationData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      name: newData.name || '',
      department: newData.department || '',
      evaluationPeriod: newData.evaluationPeriod || '',
      evaluator: newData.evaluator || '',
      responsibilityScore: newData.responsibilityScore || 0,
      taskCompletion: newData.taskCompletion || 0,
      totalScore: newData.totalScore || 0,
      grade: newData.grade || '',
      evaluationDate: newData.evaluationDate || '',
      remarks: newData.remarks || ''
    })
  } else {
    resetForm()
  }
}, { immediate: true })

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 这里应该调用API保存数据
    console.log('保存考核评价数据:', formData)
    
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>